import {Inject, Provide} from '@midwayjs/decorator';
import {InjectEntityModel} from "@midwayjs/orm";
import {RoleUser} from "../entity/roleUser";
import {Repository, getConnection, In, Not} from "typeorm";
import CommonService from "../../common/service/commonService";
import * as _ from "lodash";
import {User} from "../../user/entity/user";

@Provide()
export default class RoleUserService {
  @InjectEntityModel(RoleUser)
  roleUserModel: Repository<RoleUser>;
  @InjectEntityModel(User)
  userModel: Repository<User>;
  @Inject()
  commonService: CommonService;

/*
* 获取已分配某角色的用户*/
  async getRoleUserList(roleId:string) {
// @ts-ignore
    let roleUserList = await this.roleUserModel.find({roleId: roleId});
    let userIdArr = [];
    _.forEach(roleUserList,function (v) {
      userIdArr.push(v.userId)
    })
    // @ts-ignore
    let userList = await this.userModel.find({id: In(userIdArr)});
    return userList;

  }

  /*
  *获取未分配某角色的用户
  * */
  async getNotRoleUserList(roleId:string) {
    let userList = await this.getRoleUserList(roleId); //userList为已分配某角色的用户
    const userId:Array<string> = _.map(userList, 'id');
    let notUserList = await this.userModel.find({
      // @ts-ignore
      id: Not(In(userId)),
    });
    return notUserList;
  }

  /*
  * 保存角色与用户关系
  * */
  async save(data) {
    //获取连接并创建新的queryRunner
    const connection = getConnection();
    const queryRunner = connection.createQueryRunner();
    // 使用queryRunner建立数据库连接
    await queryRunner.connect();
    // 开始事务：
    await queryRunner.startTransaction();
    try {
      for (let i = 0; i < data.length; i++) {
        //同时成功与失败
        data[i].id = this.commonService.getUUID();
        await queryRunner.manager.save(new RoleUser(data[i]));
      }
      // 提交事务：
      await queryRunner.commitTransaction();
      return {
        success: true,
        msg: '保存成功'
      }
    }catch (e) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction();
      return {
        success: false,
        msg: '保存失败'
      }
    }
  }

  /*
 * 撤销角色与用户关系
 * */
  async delete(data) {
    const connection = getConnection();
    const queryRunner = connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      for (let i = 0; i < data.length; i++) {
        //同时成功与失败
        const userId=data[i].userId ;
        const roleId=data[i].roleId ;
        //querybuilder是性能最好的删除，属性定义可以避免sql注入
        await getConnection()
          .createQueryBuilder()
          .delete()
          .from(RoleUser)
          .where("userid = :userId AND roleId=:roleId", { userId: userId, roleId:roleId})
          .execute();
      }
      // 提交事务：
      await queryRunner.commitTransaction();
      return {
        success: true,
        msg: '撤销成功'
      }
    }catch (e) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction();
      return {
        success: false,
        msg: '撤销失败'
      }
    }
  }


}
